package br.com.velp.sudecap.servlet;

import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.List;
import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.fileupload.servlet.ServletRequestContext;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

/**
 *
 * @author duduso
 */
@Controller()
public class ImagemServlet {

    private final String UPLOAD_DIRECTORY = (System.getProperty("java.io.tmpdir") + File.separatorChar);
    private final String DIRETORIO_DEFINITIVO = (System.getProperty("user.home") + File.separator + "imagens" + File.separator);

    @RequestMapping("uploadImagem")
    public void uploadImagem(HttpServletRequest request, HttpServletResponse response) throws IOException {

        String fileDiff = request.getParameter("fileDiffName");
        boolean isMultipart = ServletFileUpload.isMultipartContent(new ServletRequestContext(request));

        if (!isMultipart) {
            return;
        }

        try {

            FileItemFactory factory = new DiskFileItemFactory();
            ServletFileUpload upload = new ServletFileUpload(factory);
            List<FileItem> itens = upload.parseRequest(request);

            if (!itens.isEmpty()) {

                FileItem item = itens.get(0);

                String fileName = item.getName();

                File uploadedFile = new File((UPLOAD_DIRECTORY + fileDiff + fileName));
                item.write(uploadedFile);

                response.setStatus(HttpServletResponse.SC_CREATED);
                response.getWriter().print("Arquivo Criado Com Sucesso!");
                response.flushBuffer();

            }

        } catch (Exception e) {

            response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                    "Um Erro Ocorreu Enquanto Tentava Criar o Arquivo: " + e.getMessage());

        }

    }

    @RequestMapping("downloadImagem")
    public void downloadImagem(HttpServletRequest request, HttpServletResponse response) throws IOException {

        String idPdm = request.getParameter("idPdm");
        String nomeArquivo = request.getParameter("nomeArquivo");
        String porcentagemReducao = request.getParameter("reducao");

        response.setContentType("image/jpeg");

        String caminhoArquivoOrigem = (idPdm != null ? (DIRETORIO_DEFINITIVO + idPdm + File.separator) : UPLOAD_DIRECTORY);

        File file = new File(caminhoArquivoOrigem + nomeArquivo);
        response.setContentLength((int) file.length());

        if (porcentagemReducao != null) {

            Integer reducao = new Integer(porcentagemReducao);

            BufferedImage bi = ImageIO.read(file);

            int width = bi.getWidth() - ((bi.getWidth() * reducao) / 100);
            int heigth = bi.getHeight() - ((bi.getHeight() * reducao) / 100);

            BufferedImage new_img = new BufferedImage(width, heigth, BufferedImage.TYPE_INT_RGB);
            Graphics2D g = new_img.createGraphics();

            g.drawImage(bi, 0, 0, width, heigth, null);

            File arquivoReduzido = new File(UPLOAD_DIRECTORY + nomeArquivo.toLowerCase().replace(".jpg", "_reduzido.jpg"));

            ImageIO.write(new_img, "JPG", arquivoReduzido);

            setResponseFile(arquivoReduzido, response);

        } else {

            setResponseFile(file, response);

        }

    }

    private void setResponseFile(File file, HttpServletResponse response) throws FileNotFoundException, IOException {

        FileInputStream in = new FileInputStream(file);
        ServletOutputStream out = response.getOutputStream();

        byte[] buf = new byte[1024];
        int count = 0;

        while ((count = in.read(buf)) >= 0) {
            out.write(buf, 0, count);
        }

        in.close();
        out.close();

    }
}
